<template>
  <drawer :show="props.show" :title="title" @close="close(false)" :show-close="true">
    <view class="sb">
      <nut-textarea
          style="height: 120rpx"
          v-model="autoAddressInfo"
          placeholder="请粘贴或输入文本，点击填”识别“自动识别姓名、联系方式和地址"
      />
      <view class="row">
        <view class="one">
          <image
              src="../../assets/images/sendAddress/fahuoxinxi_icon_yuying.png"
          ></image>
          <view class="text" @touchStart="touchStart" @touchEnd="touchEnd" style="margin-left: 12rpx">语音识别</view>
          <image
              src="../../assets/images/sendAddress/fahuoxinxi_icon_tupian.png"
              style="margin-left: 48rpx"
          ></image>
          <view class="text" @click="uploadImg" style="margin-left: 12rpx">图片识别</view>
        </view>
        <view class="tow">
          <view class="shibie_btn" @click="identityText">粘贴并识别</view>
        </view>
      </view>
    </view>
    <view class="address_del">
      <nut-form :model-value="formData">
        <view class="rows">
          <nut-form-item label="真实姓名" label-align="center">
            <nut-input
                v-model="formData.name"
                placeholder="请填写真实姓名"
                :border="false"
            />
          </nut-form-item>
        </view>
        <view class="rows">
          <nut-form-item label="联系方式" label-align="center">
            <nut-input
                v-model="formData.phone"
                placeholder="请填写手机或座机号码"
                :border="false"
            />
          </nut-form-item>
        </view>
        <view class="rows" @click="selectProvince">
          <nut-form-item label="省/市/区" label-align="center">
            <nut-input
                v-model="formData.preAdd"
                placeholder="请选择省/市/区"
                :border="false"
                readonly
            />
          </nut-form-item>
        </view>
        <view class="rows rows_address">
          <nut-form-item label="详细地址" label-align="center">
            <nut-input
                v-model="formData.address"
                placeholder="请填写精确到门牌的详细地址"
                :border="false"
            />
          </nut-form-item>
          <view class="address_icon" @click="positionAddress"></view>
        </view>
        <view class="footRows">
          <view class="default_address">
            <nut-checkbox v-model="formData.isdefault" label="复选框"
            >设为默认地址</nut-checkbox>
          </view>
          <span class="clear" @click="doClear">
            <Del2 /><span style="margin-left: 12rpx">清空当前</span>
          </span>
        </view>
      </nut-form>
      <SelectAddress
          :show="show"
          class="select_address"
          @selectAddress="selectAddress"
          @cancelSelectAddress="cancelSelectAddress"
          :showonlyTF="isFlag"
          :addressInfo="addressInfo"
      />
      <!-- <input v-model="formData.name" class="input" type="text" placeholder="请输入联系人姓名或公司姓名">
      <input v-model="formData.phone" class="input" type="text" placeholder="请输入联系手机">


      <view class="get_address">
        <input v-model="formData.address" class="input address_Input" type="text" placeholder="请填写详细地址(精确到门牌号)">
        <view class="address_icon" @click="positionAddress"></view>
      </view>

      <view class="default_address" style="border-bottom: 1px solid #ccc">
        <span>设为默认地址</span>
        <nut-switch v-model="formData.isdefault" />
      </view> -->
    </view>
    <view class="save">
      <view class="btn" @click="save">确定</view>
    </view>
  </drawer>

</template>

<script lang="ts" setup>
import drawer from '@/components/drawer'
import { ref , defineProps, defineEmits, computed, watch } from "vue";
import { AddressInfoDirection, AddressInfoDirectionCN } from "@/type";
import Taro, {useLoad} from "@tarojs/taro";
import {Del2} from "@nutui/icons-vue-taro";
import SelectAddress from "@/components/pages/addressBook/SelectAddress";
import {$upload2, addressBookUpdate, $post} from "@/@api";
import useAddressInfoStore from "@/store/addressbook";
import useUserInfoStore from "@/store/user";
import { AddressInfo } from "@/@api/AddressInfo";
import { sub } from "@/assets/js/identify/sub";
//import { getCompany } from "@/@api/order";

import useSendGoodsStore from "@/store/sendGoods"
const props = defineProps<{
  show: boolean
  type: string
  operateType: string
}>()
const emit = defineEmits<{
  //(e: 'close', args: boolean)
  (e: 'close', refresh: boolean)
}>()

const title = computed(()=>{
  return AddressInfoDirectionCN(props.type) + '人信息'
})
const isFlag = computed(()=>{
  //return AddressInfoDirection.Sender===props.type ? 'true' : 'false'
  return 'true'
})

const sendStore = useSendGoodsStore()

var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()
const voiceStr = ref<string>('')

export interface FormData {
  name: string;
  phone: string;
  address: string;
  //country: string[];
  isdefault: boolean;
  id: string;
  preAdd: string;
  latitude: string|null;
  longitude: string|null;
}

//下载qqmap-wx-jssdk,然后引入其中的js文件
let QQMapWX = require("../../assets/js/qqmap-wx-jssdk.min.js");

let qqmapsdk = new QQMapWX({
  key: "27FBZ-YPHH4-6M4UP-KLBGA-67TAV-UBBE2", // 必填
});
const show = ref<boolean>(false);
function selectProvince() {
  show.value = true;
}
const store = useAddressInfoStore();
const userStore = useUserInfoStore();
const autoAddressInfo = ref("");

const formData = ref<FormData>({
  name: "",
  phone: "",
  address: "",
  // country: [],
  isdefault: false,
  id: "",
  preAdd: "",
  latitude: "",
  longitude: "",
});
const addressInfo = ref<string[]>([]);


watch(()=>props.show,(newVal)=> {
  if(newVal){
    initRecord()
    Taro.authorize({
      scope: "scope.userLocation",
      success() {
        console.log("获取权限成功");
      },
      fail() {
        console.log("获取权限失败");
      },
    })
    if (props.operateType === 'edit' && store.addressEditParameter.addressInfo?.btcaId) {

      formData.value = {
        name: store.addressEditParameter.addressInfo?.preName,
        phone: store.addressEditParameter.addressInfo?.preTel,
        address: store.addressEditParameter.addressInfo?.preAddress.replace(
            store.addressEditParameter.addressInfo?.preAdd.split("/")[0] +
            store.addressEditParameter.addressInfo?.preAdd.split("/")[1] +
            store.addressEditParameter.addressInfo?.preAdd.split("/")[2],
            ""
        ),
        // country: store.addressEditParameter.addressInfo?.PREAREA.split(" "),
        preAdd:
            store.addressEditParameter.addressInfo?.preAdd.split("/")[0] +
            " " +
            store.addressEditParameter.addressInfo?.preAdd.split("/")[1] +
            " " +
            store.addressEditParameter.addressInfo?.preAdd.split("/")[2],
        isdefault:
            store.addressEditParameter.addressInfo?.isDefault === "1" ? true : false,
        id: store.addressEditParameter.addressInfo?.btcaId,
        latitude: store.addressEditParameter.addressInfo?.latitude,
        longitude: store.addressEditParameter.addressInfo?.longitude,
      };
      //addressInfo.value = store.addressEditParameter.addressInfo.PREAREA.split(" ");
    }
    else {
      formData.value = {
        name: "",
        phone: "",
        address: "",
        isdefault: false,
        id: "",
        preAdd: "",
        latitude: "",
        longitude: "",
      }
    }
  }
})


// console.log(store.addressEditParameter.returnInfo, "1234567");
// if (store.addressEditParameter.returnInfo == null) {
//   console.log(7777);
// } else {
//   console.log(
//     store.addressEditParameter.returnInfo,
//     "store.addressEditParameter.returnInfo"
//   );
//   const latitude = store.addressEditParameter.returnInfo.latlng.lat;
//   const longitude = store.addressEditParameter.returnInfo.latlng.lng;
//   const addressName = store.addressEditParameter.returnInfo.poiname;
//   //逆地址解析,通过经纬度获取位置等信息
//   qqmapsdk.reverseGeocoder({
//     location: { latitude, longitude },
//     success: function (res) {
//       const province = res.result.address_component.province; //省
//       const city = res.result.address_component.city; //市
//       const district = res.result.address_component.district; //区

//       addressInfo.value = [province, city, district];
//       formData.value.address = addressName;
//       store.addressEditParameter.returnInfo = null;
//     },
//     fail: function (res) {
//       store.addressEditParameter.returnInfo = null;

//       console.log(res);
//     },
//   });
// }


// 获取省市区
function selectAddress(val: string[]) {
  // formData.value.country = val;
  formData.value.preAdd = val[0] + " " + val[1] + " " + val[2];
  show.value = false;
}

function cancelSelectAddress() {
  show.value = false
}

function autoAddress() {
  const { city, county, datal, names, phone, province } = sub(
      autoAddressInfo.value
  );
  if (!city || !county || !province) {
    return Taro.showToast({
      icon: "none",
      title: "请输入正确地址",
    });
  }

  formData.value.address = datal;
  formData.value.name = names;
  // formData.value.country = [province, city, county];
  formData.value.phone = phone;
  // addressInfo.value = formData.value.country;
}

// 清空当前
function doClear() {
  formData.value = {
    name: "",
    phone: "",
    address: "",
    //  country: [],
    isdefault: false,
    id: "",
    preAdd: "",
    latitude: "",
    longitude: "",
  };
  addressInfo.value = [];
}



// 获取当前地理位置  选择地址服务
async function positionAddress() {
  console.log(process.env.TARO_ENV, "process.env.TARO_ENV");
  if (process.env.TARO_ENV === "h5") {
    Taro.navigateTo({
      url: "pages/addressBook/addressMap",
    });
  } else {
    console.log(formData.value.address)
    console.log(formData.value.preAdd)
    Taro.chooseLocation({
      latitude: formData.value.latitude,
      longitude: formData.value.longitude,
      success(res) {
        const latitude = res.latitude;
        formData.value.latitude = latitude;
        const longitude = res.longitude;
        formData.value.longitude = longitude;
        const addressName = res.name;
        //逆地址解析,通过经纬度获取位置等信息
        qqmapsdk.reverseGeocoder({
          location: { latitude, longitude },
          success: function (res) {
            const province = res.result.address_component.province; //省
            const city = res.result.address_component.city; //市
            const district = res.result.address_component.district; //区

            addressInfo.value = [province, city, district];
            formData.value.preAdd = addressInfo.value.join(' ');
            formData.value.address = addressName;
          },
          fail: function (res) {
            console.log(res);
          },
        });
      },
    });
  }
}

// 保存地址
async function save() {
  if (formData.value.name == "" || formData.value.name == null) {
    return Taro.showToast({
      icon: "none",
      title: "姓名不能为空",
    });
  }
  if (formData.value.phone == "" || formData.value.phone == null) {
    return Taro.showToast({
      icon: "none",
      title: "电话不能为空",
    });
  }
  let tel =
      /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/;
  if (!tel.test(formData.value.phone)) {
    return Taro.showToast({
      icon: "none",
      title: "请输入正确手机",
    });
  }
  if (formData.value.preAdd.length == 0) {
    return Taro.showToast({
      icon: "none",
      title: "请输入省市区",
    });
  }
  if (formData.value.address == "" || formData.value.address == null) {
    return Taro.showToast({
      icon: "none",
      title: "地址不能为空",
    });
  }
  let obj = {
    preAdd: "",
    preAddress: "",
    preAddressNote: null,
    preArea: null,
    preMobile: null,
    preName: "",
    preTel: "",
    infoType: "",
    isDefault: "",
    email: null,
    customerCode: "",
    btcaId: "",
    latitude: "",
    longitude: "",
  };
  if (props.type === AddressInfoDirection.Sender) {
    //发货地址
    obj = {
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
          formData.value.preAdd.replace(" ", "").replace(" ", "") +
          formData.value.address,
      preAddressNote: null,
      preArea: null,
      preMobile: null,
      preName: formData.value.name,
      preTel: formData.value.phone,
      latitude: formData.value.latitude,
      longitude: formData.value.longitude,
      infoType: "1",
      isDefault: formData.value.isdefault ? "1" : "0",
      email: null,
      customerCode: userStore.userInfo.customerCode,
      btcaId: formData.value.id,
    };
  } else {
    //收货地址
    obj = {
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
          formData.value.preAdd.replace(" ", "").replace(" ", "") +
          formData.value.address,
      preAddressNote: null,
      preArea: null,
      preMobile: null,
      preName: formData.value.name,
      preTel: formData.value.phone,
      latitude: formData.value.latitude,
      longitude: formData.value.longitude,
      infoType: "2",
      isDefault: formData.value.isdefault ? "2" : "0",
      email: null,
      customerCode: userStore.userInfo.customerCode,
      btcaId: formData.value.id,
    };
  }

  if(!formData.value.id){
    obj.opFlag = '0'
  }

  const res = await addressBookUpdate(obj);
  if (res == 200) {
    close(true)
    Taro.showToast({
      icon: "success",
      title: "成功",
    });
    if(props.type === AddressInfoDirection.Sender){
      sendStore.sendAddressInfo = obj
    }
    else{
      sendStore.getAddressInfo = obj
    }
  }
  if (store.addressEditParameter.addressInfo) {
    let savedAddressInfo: AddressInfo | null = {
      ...store.addressEditParameter.addressInfo,
      preName: formData.value.name,
      preTel: formData.value.phone,
      preAdd: formData.value.preAdd.replace(" ", "/").replace(" ", "/"),
      preAddress:
          formData.value.preAdd.replace(" ", "").replace(" ", "") +
          formData.value.address,
    };

    if (store.addressEditParameter.onEditComplete) {
      store.addressEditParameter.onEditComplete(savedAddressInfo)
    }
  }
}

function close(refresh) {
  addressInfo.value = []
  emit('close', refresh)
}



const initRecord = ()=>{
  console.log(manager)
  Taro.authorize({
    scope: 'scope.record',
    success(res) {
      console.log(res)
    }
  })
  manager.onStart = function (res) {
    console.log("成功开始录音识别", res)
  }
  manager.onError = function (res) {
    console.error("error msg", res)
    if(res.retcode==-30003){
      Taro.showToast({
            icon: 'none',
            title: '长按进行录音'
          })
    }else{
      Taro.showToast({
            icon: 'none',
            title: '语音识别失败，请重试'
          })
    }
  }
  manager.onRecognize = (res) => {
    console.log(res.result,111)
    voiceStr.value += res.result
  }
// 识别结束事件
  manager.onStop = (res) => {
    console.log(res.result,222)
    voiceStr.value = res.result || ''
    autoAddressInfo.value=voiceStr.value.slice(0,-1)
  }
}

//语音识别
const touchStart = ()=>{
  console.log('start')
  voiceStr.value = ''
  manager.start({
    lang: 'zh_CN',
    duration: 60000,
  })
}
const touchEnd = ()=>{
  console.log('end')
  manager.stop()
  console.log(333)
}

//上传图片识别
const uploadImg = ()=> {
  Taro.chooseImage({
    count: 1,
    sizeType: 'original',
    success: async (res)=>{
      console.log(res.tempFilePaths[0])
      Taro.showLoading({
        title: '识别中',
      })
      const imgRes = await $upload2('/selfmachine-system/image/pictureAnalysis','file', res.tempFilePaths[0])
      Taro.hideLoading()
      const resData = JSON.parse(imgRes.data)
      if(resData.code ==200){
        Taro.showToast({
          icon: 'none',
          title: '图片识别成功'
        })
        autoAddressInfo.value = resData.data
      }
    },
    fail: (err)=>{
      Taro.hideLoading()
      // Taro.showToast({
      //   icon: 'error',
      //   title: '图片识别失败'
      // })
    }
  })
}

const identityText = async ()=>{
  // console.log('转换前',autoAddressInfo.value)
  // console.log('转换后',identityString.processAddress(autoAddressInfo.value))
  // let result:any = identityString.processAddress(autoAddressInfo.value)
  // formData.value.name = result.name || ''
  // formData.value.phone = result.phone || ''
  // formData.value.address = result.address || ''
  Taro.showLoading({
    title: '识别中',
  })
  const res:any = await $post('/selfmachine-system/addressBook/address/resolution',{content:autoAddressInfo.value})
  Taro.hideLoading()
  if(res.data.code==200 && res.data.data.length){
    formData.value.name = res.data.data[0].name || ''
    formData.value.phone = (res.data.data[0].mobile && res.data.data[0].mobile.length) ? res.data.data[0].mobile[0] : ''
    addressInfo.value = [res.data.data[0].xzq.province ? (res.data.data[0].xzq.province+'省') : '',res.data.data[0].xzq.city || '',res.data.data[0].xzq.district || '']
    formData.value.preAdd = addressInfo.value.join(' ')
    formData.value.address = res.data.data[0].xzq.subArea || ''



    qqmapsdk.geocoder({
      address: addressInfo.value.join('')+formData.value.address,
      success: function (res) {
        if(res.result){
          formData.value.latitude = res.result.location.lat || ''
          formData.value.longitude = res.result.location.lng || ''
        }
        else{
          Taro.showToast({
            icon: 'none',
            title: '地理位置解析失败'
          })
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  }


}

</script>

<style lang="scss">
.sb {
  background-color: white;
  width: 100%;
  height: 216rpx;
  border-radius: 0;
  border-bottom: 16rpx #f5f5f5 solid;
  .nut-textarea {
    border-radius: 24rpx;
    padding: 10rpx 30rpx;
    box-sizing: border-box;
  }
  .row {
    width: 100%;
    height: 56rpx;
    // background-color: red;
    display: flex;
    .one {
      width: calc(100% - 201rpx);
      height: 100%;
      display: flex;
      align-items: center;
      padding-left: 24rpx;
      box-sizing: border-box;
      image {
        width: 32rpx;
        height: 32rpx;
      }
      .text {
        font-size: 24rpx;
        font-family: PingFangSC-Regular;
      }
    }
    .tow {
      width: 176rpx;
      height: 100%;
      .shibie_btn {
        width: 176rpx;
        height: 56rpx;
        border-radius: 28rpx;
        background: #0966ff;

        font-family: PingFang SC Bold;
        font-size: 26rpx;
        color: #ffffff;
        text-align: center;
        line-height: 56rpx;
      }
    }
  }
}
.address_del {
  border-radius: 0;
  background-color: white;
  height: 520rpx;
  width: 702rpx;
  margin-left: 24rpx;
  margin-top: 16rpx;
  border-bottom: 16rpx #f5f5f5 solid;
  .footRows {
    width: 702rpx;
    height: 104rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .default_address {
      display: flex;
      justify-content: space-between;
      height: 50rpx;
      align-items: center;
      padding: 20rpx;
      .nut-checkbox__label {
        margin-left: 10rpx;
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        color: #666666;
      }
    }

    .clear {
      margin-right: 50rpx;
      color: #666;
      font-family: PingFangSC-Regular;
      font-size: 24rpx;
      display: flex;
      span {
        display: flex;
        align-items: center;
      }
    }
  }
  .rows {
    width: 702rpx;
    height: 103rpx;
    border-bottom: 1rpx solid #f4f5f6;
    display: flex;
    align-items: center;
    .nut-form-item__label {
      font-family: PingFang SC Medium;
      font-size: 28rpx;
      color: #666666;
    }
    .nut-input {
      font-family: PingFang SC;
      font-size: 28rpx;
      color: #999999;
    }
    .nut-cell {
      padding: 0;
    }
    &.rows_address {
      .nut-cell::after {
        border: none;
      }
    }
  }
}
.input {
  padding: 40rpx;
  border-bottom: 1px solid #ccc;
}
.save {
  width: 100%;
  background-color: #fff;
  padding: 20rpx 0;
  .btn {
    width: calc(100% - 48rpx);
    height: 80rpx;
    margin-left: 24rpx;
    border-radius: 40rpx;
    background-color: #0966ff;
    color: #fff;
    text-align: center;
    line-height: 80rpx;
  }
}
.get_address {
  display: flex;
  border-bottom: 1px solid #ccc;

  .address_Input {
    flex: 1;
    padding: 40rpx;
    border-bottom: none;
  }
}
.address_icon {
  width: 70rpx;
  height: 70rpx;
  line-height: 100rpx;
  background: url(../../assets/images/index/服务查询/wangdianchaxun_icon_chakanditu@2x.png) no-repeat center;
  margin-right: 25rpx;
}
.tabBody .line {

}
</style>
